/*
 * @Author: 肖思汗 
 * @Date: 2025-07-10 10:06:40 
 * @Last Modified by: 肖思汗
 * @Last Modified time: 2025-07-24 16:25:19
 */


import { ReactNode, useEffect, useRef, useState } from 'react';
import styles from './devTool.module.less';
import { observer } from "mobx-react-lite";
import utilsStore from 'src/utils/utilsStore';
import PageLayer from 'src/components/PageLayer/PageLayer';
import { Button, Canvas, View, Image } from '@tarojs/components';
import UtTag from 'src/components/UtTag/UtTag';
import Taro from '@tarojs/taro';
import { toJS } from 'mobx';
import utils from 'src/utils/utils';
import loadSVGFromURL from './loadSVGFromURL';

interface Iprops {
    children?: ReactNode
}

// 组件
const DevTool = observer((props: Iprops) => {

    const [base64Length, setBase64Length] = useState(0);
    const [webglBase64Length, setWebglBase64Length] = useState(0);

    const [systemInfo, setSystemInfo] = useState<any>(null);

    const canvasRef = useRef<Taro.Canvas | null>(null);
    const ctx = useRef<CanvasRenderingContext2D | null>(null);
    const webglCanvasRef = useRef<Taro.Canvas | null>(null);
    const gl = useRef<WebGLRenderingContext | null>(null);

    const [imagePath, setImagePath] = useState<string>('');

    useEffect(() => {
        const getSystemInfo = async () => {
            try {
                const info = await Taro.getSystemInfo();
                setSystemInfo(info);
            } catch (error) {
                console.error('获取系统信息失败:', error);
            }
        };
        getSystemInfo();

        const initGlAndCtx = async () => {

            // 获取2D Canvas
            const canvas2d = await new Promise<any>((resolve, reject) => {
                Taro.createSelectorQuery().select('#canvas2d')
                    .fields({ node: true, size: true })
                    .exec(res => res[0] ? resolve(res[0].node) : reject('未找到2D Canvas'));
            });

            canvasRef.current = canvas2d;
            canvas2d.width = 512;
            canvas2d.height = 512;
            ctx.current = canvas2d.getContext('2d');

            // 获取WebGL Canvas
            const webglCanvas = await new Promise<any>((resolve, reject) => {
                Taro.createSelectorQuery().select('#webglCanvas')
                    .fields({ node: true, size: true })
                    .exec(res => res[0] ? resolve(res[0].node) : reject('未找到WebGL Canvas'));
            });

            webglCanvasRef.current = webglCanvas;
            webglCanvas.width = 512;
            webglCanvas.height = 512;
            gl.current = webglCanvas.getContext('webgl', { preserveDrawingBuffer: true }) || webglCanvas.getContext('experimental-webgl', { preserveDrawingBuffer: true });
        };

        initGlAndCtx();

    }, []);


    // webGL to 2d
    const drawCombined = async () => {

        if (webglCanvasRef.current && gl.current && canvasRef.current && ctx.current) {
            // 将WebGL内容绘制到2D Canvas
            //@ts-ignore
            ctx.current.drawImage(webglCanvasRef.current, 0, 0, 512, 512);
            // 读取像素数据
            // const pixels = new Uint8Array(512 * 512 * 4);
            // gl.current.readPixels(0, 0, 512, 512, gl.current.RGBA, gl.current.UNSIGNED_BYTE, pixels);

            // // 写入2D Canvas
            // Taro.canvasPutImageData({
            //     canvasId: "canvas2d",
            //     data: new Uint8ClampedArray(pixels.buffer),
            //     width: 512,
            //     height: 512,
            //     x: 0,
            //     y: 0,
            //     success: () => {
            //     }
            // })

            // if (canvasRef.current) {
            //     //@ts-ignore
            //     const imageData: ImageData = canvasRef.current.createImageData(new Uint8ClampedArray(pixels), 512, 512);
            //     // console.log("imageData", imageData);
            //     // imageData 绘制到 canvas2d
            //     if (ctx.current) {
            //         ctx.current.putImageData(imageData, 0, 0);
            //     }
            // }

        }

        console.log('Canvas内容合并完成');
    };

    // WebGL绘图处理
    const drawWebGL = async () => {

        if (webglCanvasRef.current && gl.current && canvasRef.current && ctx.current) {
            // 设置视口
            gl.current.viewport(0, 0, 512, 512);

            // 设置透明背景
            gl.current.clearColor(0.0, 0.0, 0.0, 0.0);
            gl.current.clear(gl.current.COLOR_BUFFER_BIT);

            // 启用透明度
            gl.current.enable(gl.current.BLEND);
            gl.current.blendFunc(gl.current.SRC_ALPHA, gl.current.ONE_MINUS_SRC_ALPHA);

            // 顶点着色器
            const vsSource = `
                    attribute vec2 position;
                    void main() {
                        gl_Position = vec4(position, 0.0, 1.0);
                    }
                `;

            // 片段着色器
            const fsSource = `
                    void main() {
                        gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0); // 红色
                    }
                `;

            // 初始化着色器
            const vertexShader = gl.current.createShader(gl.current.VERTEX_SHADER);
            gl.current.shaderSource(vertexShader!, vsSource);
            gl.current.compileShader(vertexShader!);

            const fragmentShader = gl.current.createShader(gl.current.FRAGMENT_SHADER);
            gl.current.shaderSource(fragmentShader!, fsSource);
            gl.current.compileShader(fragmentShader!);

            const program = gl.current.createProgram();
            gl.current.attachShader(program, vertexShader!);
            gl.current.attachShader(program, fragmentShader!);
            gl.current.linkProgram(program);
            gl.current.useProgram(program);

            // 三角形顶点数据
            const vertices = new Float32Array([
                -1, -1,   // 顶点1
                Math.random(), -1, // 顶点2
                -1, Math.random()   // 顶点3
            ]);

            const buffer = gl.current.createBuffer();
            gl.current.bindBuffer(gl.current.ARRAY_BUFFER, buffer);
            gl.current.bufferData(gl.current.ARRAY_BUFFER, vertices, gl.current.STATIC_DRAW);

            const positionLocation = gl.current.getAttribLocation(program, 'position');
            gl.current.enableVertexAttribArray(positionLocation);
            gl.current.vertexAttribPointer(positionLocation, 2, gl.current.FLOAT, false, 0, 0);

            // 创建帧缓冲区
            const framebuffer = gl.current.createFramebuffer();
            const texture = gl.current.createTexture();

            // 配置纹理
            gl.current.bindTexture(gl.current.TEXTURE_2D, texture);
            gl.current.texImage2D(gl.current.TEXTURE_2D, 0, gl.current.RGBA, 512, 512,
                0, gl.current.RGBA, gl.current.UNSIGNED_BYTE, null);
            gl.current.texParameteri(gl.current.TEXTURE_2D, gl.current.TEXTURE_MIN_FILTER, gl.current.LINEAR);

            // 绑定帧缓冲区
            gl.current.bindFramebuffer(gl.current.FRAMEBUFFER, framebuffer);
            gl.current.framebufferTexture2D(gl.current.FRAMEBUFFER, gl.current.COLOR_ATTACHMENT0,
                gl.current.TEXTURE_2D, texture, 0);

            // 检查帧缓冲区状态
            if (gl.current.checkFramebufferStatus(gl.current.FRAMEBUFFER) !== gl.current.FRAMEBUFFER_COMPLETE) {
                console.error('帧缓冲区配置不完整');
            }

            // 绘制到帧缓冲区
            gl.current.drawArrays(gl.current.TRIANGLES, 0, 3);

            // 解绑帧缓冲区
            gl.current.bindFramebuffer(gl.current.FRAMEBUFFER, null);

            // 将帧缓冲区内容绘制到默认缓冲区
            gl.current.bindTexture(gl.current.TEXTURE_2D, texture);

            // 使用简单着色器将纹理绘制到屏幕
            const screenVsSource = `
                            attribute vec2 position;
                            varying vec2 v_texCoord;
                            void main() {
                                gl_Position = vec4(position, 0.0, 1.0);
                                v_texCoord = position * 0.5 + 0.5;
                            }
                        `;

            const screenFsSource = `
                            precision mediump float;
                            varying vec2 v_texCoord;
                            uniform sampler2D u_texture;
                            void main() {
                                gl_FragColor = texture2D(u_texture, v_texCoord);
                            }
                        `;

            // 初始化屏幕着色器
            const screenVertexShader = gl.current.createShader(gl.current.VERTEX_SHADER);
            gl.current.shaderSource(screenVertexShader!, screenVsSource);
            gl.current.compileShader(screenVertexShader!);

            const screenFragmentShader = gl.current.createShader(gl.current.FRAGMENT_SHADER);
            gl.current.shaderSource(screenFragmentShader!, screenFsSource);
            gl.current.compileShader(screenFragmentShader!);

            const screenProgram = gl.current.createProgram();
            gl.current.attachShader(screenProgram, screenVertexShader!);
            gl.current.attachShader(screenProgram, screenFragmentShader!);
            gl.current.linkProgram(screenProgram);
            gl.current.useProgram(screenProgram);

            // 设置全屏四边形
            const screenVertices = new Float32Array([
                -1.0, -1.0,
                1.0, -1.0,
                -1.0, 1.0,
                1.0, 1.0
            ]);

            const screenBuffer = gl.current.createBuffer();
            gl.current.bindBuffer(gl.current.ARRAY_BUFFER, screenBuffer);
            gl.current.bufferData(gl.current.ARRAY_BUFFER, screenVertices, gl.current.STATIC_DRAW);

            const screenPositionLoc = gl.current.getAttribLocation(screenProgram, 'position');
            gl.current.enableVertexAttribArray(screenPositionLoc);
            gl.current.vertexAttribPointer(screenPositionLoc, 2, gl.current.FLOAT, false, 0, 0);

            // 绘制全屏四边形
            gl.current.drawArrays(gl.current.TRIANGLE_STRIP, 0, 4);
        }
    }

    const draw2D = () => {
        try {
            const query = Taro.createSelectorQuery();
            query.select('#canvas2d')
                .fields({ node: true, size: true })
                .exec((res) => {
                    if (res[0]) {
                        const canvas = res[0].node;
                        const ctx = canvas.getContext('2d');
                        // 设置Canvas尺寸
                        canvas.width = 512;
                        canvas.height = 512;
                        ctx.clearRect(0, 0, 512, 512);
                        // 绘制绿色正方形
                        ctx.fillStyle = '#4CAF50';
                        ctx.fillRect(6, 6, 500, 500);
                        console.log('2D Canvas绘制完成');
                    } else {
                        console.error('未获取到2D Canvas元素');
                    }
                });
        } catch (error) {
            console.error('2D绘图失败:', error);
        }
    };

    useEffect(() => {
        // 2D绘制绿色正方形
        setTimeout(() => {
            // draw2D();
            // drawWebGL();
        }, 300);
    }, []);

    const drawType = useRef(0);

    return (
        <PageLayer
            title="开发调试页面"
            showBack={true}
            className={styles.devTool}
            hasHeader={true}
            hasTabBar={true}
        >
            <View>
                屏幕的高度:{utilsStore.windowHeight}
            </View>

            <View>
                屏幕的宽度:{utilsStore.windowWidth}
            </View>

            <UtTag
                style={{
                    position: 'absolute',
                    top: utilsStore.safeAreaTop,
                    left: utilsStore.windowWidth / 2,
                }}
            >
                顶部安全距离:{utilsStore.safeAreaTop}
            </UtTag>

            <UtTag
                style={{
                    position: 'absolute',
                    top: utilsStore.titleTop,
                    left: utilsStore.windowWidth / 2,
                }}
            >
                顶部安全距离+标题的高度:{utilsStore.titleTop}
            </UtTag>

            <UtTag
                style={{
                    position: 'absolute',
                    bottom: utilsStore.safeAreaBottom,
                    left: utilsStore.windowWidth / 2,
                }}
            >
                底部部安全距离:{utilsStore.safeAreaBottom}
            </UtTag>

            <UtTag
                style={{
                    position: 'absolute',
                    bottom: utilsStore.barBottom,
                    left: utilsStore.windowWidth / 2,
                }}
            >
                底部安全距离+tabBar的高度:{utilsStore.barBottom}
            </UtTag>

            <View
                style={{
                    display: 'flex',
                    justifyContent: 'space-evenly',
                    marginTop: '20px',
                    marginBottom: '20px',
                }}
            >
                <Canvas
                    id="webglCanvas"
                    canvasId="webglCanvas"
                    style={{ width: '42vw', height: '42vw', border: '1px solid #ccc' }}
                    type="webgl"
                    onClick={async () => {
                        Taro.showLoading({ title: '正在渲染' });
                        await drawWebGL();
                        await new Promise(resolve => setTimeout(resolve, 1000));
                        await drawWebGL();
                        await new Promise(resolve => setTimeout(resolve, 1000));
                        if (webglCanvasRef.current && gl.current && canvasRef.current && ctx.current) {
                            // 将 WebGL 内容绘制到离屏 Canvas
                            // ctx.current.clearRect(0, 0, 1024, 1024);
                            const base64 = webglCanvasRef.current.toDataURL('image/png', 1);
                            console.log("base64Lenth", base64.length);
                            console.log(base64.substring(0, 200), "...");
                            const filePath = `${Taro.env.USER_DATA_PATH}/${new Date().valueOf()}.png`;
                            Taro.getFileSystemManager().writeFile({
                                filePath: filePath,
                                data: base64.replace(/^data:image\/\w+;base64,/, ''),
                                encoding: 'base64',
                                success: () => {
                                    console.log(filePath);
                                    // setImagePath(filePath);
                                    Taro.hideLoading();
                                    Taro.previewImage({
                                        urls: [filePath],
                                    });
                                    console.log('文件保存成功');
                                },
                                fail: () => {
                                    console.log('文件保存失败');
                                }
                            });
                        }
                    }}
                />
                <Canvas
                    ref={canvasRef}
                    id="canvas2d"
                    canvasId="canvas2d"
                    style={{ width: '42vw', height: '42vw', border: '1px solid #ccc' }}
                    type="2d"
                    onClick={() => {
                        Taro.canvasToTempFilePath({
                            x: 0,
                            y: 0,
                            width: 512,
                            height: 512,
                            destWidth: 512,
                            destHeight: 512,
                            canvas: canvasRef.current!,
                            success: (res) => {
                                console.log(res.tempFilePath);
                                Taro.previewImage({
                                    urls: [res.tempFilePath],
                                });
                            }
                        });
                    }}
                />

            </View>

            <View
                style={{
                    display: 'flex',
                    justifyContent: 'space-evenly',
                    marginTop: '20px',
                    marginBottom: '20px',
                }}
            >
                <Image
                    style={{ width: '42vw', height: '42vw', border: '1px solid #ccc' }}
                    src={imagePath}
                />
            </View>

            <View
                style={{
                    margin: "20px"
                }}
            >
                <View>base64Length : {base64Length}</View>
                <View>webglBase64Length : {webglBase64Length}</View>
                <View>发版时间 : 2025年7月21日16:11:42</View>
            </View>

            <Button
                onClick={() => {
                    drawCombined();
                }}
            >webGL to 2d</Button>

            <Button
                onClick={() => {
                    console.log("Taro.getSystemInfoSync()", toJS(Taro.getSystemInfoSync()));
                    console.log("Taro.getDeviceInfo()", toJS(Taro.getDeviceInfo()));
                }}
            >设备信息</Button>

            <Button
                onClick={() => {
                    loadSVGFromURL(utils.ossSuffix("/img/213_150_3030_28e7f1c8825763cc411131aacd69baf3.svg")
                        // (objects, options) => {
                        //     console.log("objects", objects);
                        //     console.log("options", options);
                        //     // 将 SVG 元素转换为 Fabric 对象（关键步骤）
                        //     //@ts-ignore
                        //     const svgGroup = util.groupSVGElements(objects, options);
                        //     console.log("svgGroup", svgGroup);
                        //     // // 或者直接使用整个 SVG 组合（推荐）
                        //     const clipPath = svgGroup;
                        //     this.clipPath = clipPath;
                        //     this.dirty = true;
                        //     const { width, height } = clipPath;
                        //     const minScale = Math.min(this.width! / width!, this.height! / height!);
                        //     clipPath.left = minScale * width! / -2;
                        //     clipPath.top = minScale * height! / -2;
                        //     clipPath.scaleX = minScale;
                        //     clipPath.scaleY = minScale;
                        //     this.canvas?.renderAll();
                        // }
                    ).then((image) => {
                        console.log("image", image);
                    })
                }}
            >
                解析svg
            </Button>

            <View style={{ marginTop: '20px' }}>

                <View style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5' }}>
                    <View style={{ fontWeight: 'bold', marginBottom: '5px' }}>运行环境</View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        开发版: {utils.isDev ? '是' : '否'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        体验版: {utils.isTrial ? '是' : '否'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        线上版: {utils.isRelease ? '是' : '否'}
                    </View>
                </View>

                <View style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5' }}>
                    <View style={{ fontWeight: 'bold', marginBottom: '5px' }}>设备基本信息</View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        设备品牌: {systemInfo?.brand || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        设备型号: {systemInfo?.model || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        操作系统: {systemInfo?.system || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        语言: {systemInfo?.language || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        微信版本: {systemInfo?.version || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        基础库版本: {systemInfo?.SDKVersion || '未知'}
                    </View>
                </View>

                <View style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5' }}>
                    <View style={{ fontWeight: 'bold', marginBottom: '5px' }}>屏幕信息</View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        屏幕宽度: {systemInfo?.screenWidth || '未知'}px
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        屏幕高度: {systemInfo?.screenHeight || '未知'}px
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        窗口宽度: {systemInfo?.windowWidth || '未知'}px
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        窗口高度: {systemInfo?.windowHeight || '未知'}px
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        像素比: {systemInfo?.pixelRatio || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        状态栏高度: {systemInfo?.statusBarHeight || '未知'}px
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        字体大小: {systemInfo?.fontSizeSetting || '未知'}px
                    </View>
                </View>

                <View style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5' }}>
                    <View style={{ fontWeight: 'bold', marginBottom: '5px' }}>权限信息</View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        相册权限: {systemInfo?.albumAuthorized !== undefined ? (systemInfo.albumAuthorized ? '已授权' : '未授权') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        摄像头权限: {systemInfo?.cameraAuthorized !== undefined ? (systemInfo.cameraAuthorized ? '已授权' : '未授权') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        定位权限: {systemInfo?.locationAuthorized !== undefined ? (systemInfo.locationAuthorized ? '已授权' : '未授权') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        麦克风权限: {systemInfo?.microphoneAuthorized !== undefined ? (systemInfo.microphoneAuthorized ? '已授权' : '未授权') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        通知权限: {systemInfo?.notificationAuthorized !== undefined ? (systemInfo.notificationAuthorized ? '已授权' : '未授权') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        日历权限: {systemInfo?.phoneCalendarAuthorized !== undefined ? (systemInfo.phoneCalendarAuthorized ? '已授权' : '未授权') : '不支持'}
                    </View>
                </View>

                <View style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5' }}>
                    <View style={{ fontWeight: 'bold', marginBottom: '5px' }}>系统开关</View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        蓝牙: {systemInfo?.bluetoothEnabled !== undefined ? (systemInfo.bluetoothEnabled ? '已开启' : '已关闭') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        定位: {systemInfo?.locationEnabled !== undefined ? (systemInfo.locationEnabled ? '已开启' : '已关闭') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        Wi-Fi: {systemInfo?.wifiEnabled !== undefined ? (systemInfo.wifiEnabled ? '已开启' : '已关闭') : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        调试模式: {systemInfo?.enableDebug !== undefined ? (systemInfo.enableDebug ? '已开启' : '已关闭') : '未知'}
                    </View>
                </View>

                <View style={{ marginBottom: '15px', padding: '10px', backgroundColor: '#f5f5f5' }}>
                    <View style={{ fontWeight: 'bold', marginBottom: '5px' }}>其他信息</View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        平台: {systemInfo?.platform || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        设备性能等级: {systemInfo?.benchmarkLevel !== undefined ? systemInfo.benchmarkLevel : '不支持'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        主题: {systemInfo?.theme || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        设备方向: {systemInfo?.deviceOrientation || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        运行环境: {systemInfo?.environment || '未知'}
                    </View>
                    <View style={{ margin: '10px', padding: '5px', border: '1px solid #eee' }}>
                        Taro环境: {Taro.env.TARO_ENV || '未知'}
                    </View>
                </View>



            </View>


            <View
                style={{
                    padding: "20px",
                }}
            ></View>

        </PageLayer>
    );

});

export default DevTool;